package com.colbby.datahouse.lock;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地锁
 * @author liujingyu
 * @Date 2013-10-12
 *
 */
public class LocalLock<T> implements Lock<T>{

	private ManagedPool<ObjectLock<T>> pool = new ManagedPool<>();
	private static final Logger logger = LoggerFactory.getLogger(LocalLock.class);

	
	@Override
	public void lock(T t) {
		ObjectLock<T> lock = new ObjectLock<T>(t);
		lock = pool.internAndRecord(lock);
		lock.lock();
		logger.info("加锁" + t);
	}

	@Override
	public boolean tryLock(T t) {
		ObjectLock<T> lock = new ObjectLock<T>(t);
		lock = pool.internAndRecord(lock);
		if(lock.tryLock()) {
			logger.info("加锁" + t);
			return true;
		} else {
			pool.destroy(lock);
			return false;
		}
	}

	@Override
	public boolean tryLock(T t, long time, TimeUnit timeUnit) throws InterruptedException  {
		ObjectLock<T> lock = new ObjectLock<T>(t);
		lock = pool.internAndRecord(lock);
		try {
			if(lock.tryLock(time, timeUnit)) {
				logger.info("加锁" + t);
				return true;
			} else {
				pool.destroy(lock);
				return false;
			}
		} catch (InterruptedException e) {
			pool.destroy(lock);
			throw e;
		}
	}
	
	@Override
	public void unlock(T t) {
		ObjectLock<T> lock = new ObjectLock<T>(t);
		lock = pool.destroy(lock);
		if(lock != null) {
			logger.info("解锁" + t);
			lock.unlock();
		} else {
			logger.info("锁机制有问题，请检查" + t);
		}
	}
}
